package com.xtayfjpk.zookeeper.test.master_workers.callback.master;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.KeeperException.Code;

import com.xtayfjpk.zookeeper.test.master_workers.Master;
import com.xtayfjpk.zookeeper.test.master_workers.Master.MasterStates;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseStringCallback;


public class MasterCreateCallback extends BaseStringCallback implements StringCallback {
	private static final Logger LOGGER = Logger.getLogger(MasterCreateCallback.class);
	private Master master;
	
	public MasterCreateCallback(Master master) {
		this.master = master;
	}

	@Override
	public void processResult(int rc, String path, Object ctx, String name) {
		super.processResult(rc, path, ctx, name);
		LOGGER.info("I'm " + (master.getState() == MasterStates.ELECTED ? "" : "not ") + "the leader " + master.getServerId());
	}
	
	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			String name) {
		master.checkMaster();
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, String name) {
		master.setState(MasterStates.ELECTED);
		master.takeLeadership();
	}
	
	@Override
	protected void nodeExistsCaseAction(int rc, String path, Object ctx, String name) {
		/**
		 * 创建/master节点时，如果该节点已经存在了，则说明有另一个worker成为了master
		 */
		master.setState(MasterStates.NOTELECTED);
		master.exists();
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			String name) {
		master.setState(MasterStates.NOTELECTED);
		LOGGER.error("Something went wrong when running for master.", 
                KeeperException.create(Code.get(rc), path));
	}
}
